//! 规则引擎模块
//! 
//! 提供多层级规则继承系统、正则表达式编译优化和自定义函数hook机制

use crate::error::{DataForgeError, Result};
use crate::memory::StringPool;
use rand::distributions::Distribution;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};


/// 规则类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RuleType {
    /// 正则表达式规则
    Regex { pattern: String, flags: Option<String> },
    /// 范围规则
    Range { min: Value, max: Value },
    /// 枚举规则
    Enum { values: Vec<Value> },
    /// 长度规则
    Length { min: Option<usize>, max: Option<usize> },
    /// 格式规则
    Format { format: String },
    /// 自定义规则
    Custom { name: String, params: HashMap<String, Value> },
    /// 组合规则
    Composite { operator: LogicalOperator, rules: Vec<Rule> },
}

/// 逻辑操作符
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum LogicalOperator {
    And,
    Or,
    Not,
}

/// 规则定义
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Rule {
    /// 规则ID
    pub id: String,
    /// 规则名称
    pub name: String,
    /// 规则类型
    pub rule_type: RuleType,
    /// 优先级
    pub priority: u32,
    /// 是否启用
    pub enabled: bool,
    /// 描述
    pub description: Option<String>,
    /// 标签
    pub tags: Vec<String>,
    /// 父规则ID（用于继承）
    pub parent_id: Option<String>,
}

/// 规则上下文
#[derive(Debug, Clone)]
pub struct RuleContext {
    /// 字段名
    pub field_name: String,
    /// 当前值
    pub current_value: Option<Value>,
    /// 额外参数
    pub params: HashMap<String, Value>,
    /// 生成历史
    pub generation_history: Vec<Value>,
}

/// 规则执行结果
#[derive(Debug, Clone)]
pub struct RuleResult {
    /// 是否匹配
    pub matched: bool,
    /// 生成的值
    pub value: Option<Value>,
    /// 错误信息
    pub error: Option<String>,
    /// 执行时间
    pub execution_time: std::time::Duration,
}

/// 自定义规则处理器
pub trait CustomRuleHandler: Send + Sync {
    /// 处理自定义规则
    fn handle(&self, rule: &Rule, context: &RuleContext) -> Result<RuleResult>;
    
    /// 获取处理器名称
    fn name(&self) -> &str;
}

/// 规则引擎
pub struct RuleEngine {
    /// 规则存储
    rules: RwLock<HashMap<String, Rule>>,
    /// 编译后的正则表达式缓存
    regex_cache: RwLock<HashMap<String, Regex>>,
    /// 自定义规则处理器
    custom_handlers: RwLock<HashMap<String, Arc<dyn CustomRuleHandler>>>,
    /// 字符串池
    string_pool: Arc<StringPool>,
    /// 规则继承关系
    inheritance_tree: RwLock<HashMap<String, Vec<String>>>,
}

impl RuleEngine {
    /// 创建新的规则引擎
    pub fn new(string_pool: Arc<StringPool>) -> Self {
        Self {
            rules: RwLock::new(HashMap::new()),
            regex_cache: RwLock::new(HashMap::new()),
            custom_handlers: RwLock::new(HashMap::new()),
            string_pool,
            inheritance_tree: RwLock::new(HashMap::new()),
        }
    }

    /// 添加规则
    pub fn add_rule(&self, rule: Rule) -> Result<()> {
        let rule_id = rule.id.clone();
        
        // 验证规则
        self.validate_rule(&rule)?;
        
        // 更新继承关系
        if let Some(parent_id) = &rule.parent_id {
            let mut tree = self.inheritance_tree.write().unwrap();
            tree.entry(parent_id.clone()).or_insert_with(Vec::new).push(rule_id.clone());
        }
        
        // 存储规则
        let mut rules = self.rules.write().unwrap();
        rules.insert(rule_id, rule);
        
        Ok(())
    }

    /// 删除规则
    pub fn remove_rule(&self, rule_id: &str) -> Result<()> {
        let mut rules = self.rules.write().unwrap();
        
        if let Some(rule) = rules.remove(rule_id) {
            // 清理继承关系
            if let Some(parent_id) = &rule.parent_id {
                let mut tree = self.inheritance_tree.write().unwrap();
                if let Some(children) = tree.get_mut(parent_id) {
                    children.retain(|id| id != rule_id);
                }
            }
            
            // 清理正则表达式缓存
            if let RuleType::Regex { pattern, .. } = &rule.rule_type {
                let mut cache = self.regex_cache.write().unwrap();
                cache.remove(pattern);
            }
            
            Ok(())
        } else {
            Err(DataForgeError::validation(&format!("Rule not found: {}", rule_id)))
        }
    }

    /// 执行规则
    pub fn execute_rule(&self, rule_id: &str, context: &RuleContext) -> Result<RuleResult> {
        let start_time = std::time::Instant::now();
        
        let rule = {
            let rules = self.rules.read().unwrap();
            rules.get(rule_id)
                .ok_or_else(|| DataForgeError::validation(&format!("Rule not found: {}", rule_id)))?
                .clone()
        };

        if !rule.enabled {
            return Ok(RuleResult {
                matched: false,
                value: None,
                error: Some("Rule is disabled".to_string()),
                execution_time: start_time.elapsed(),
            });
        }

        let result = self.execute_rule_internal(&rule, context);
        
        Ok(RuleResult {
            matched: result.is_ok(),
            value: result.as_ref().ok().cloned(),
            error: result.as_ref().err().map(|e| e.to_string()),
            execution_time: start_time.elapsed(),
        })
    }

    /// 内部规则执行逻辑
    fn execute_rule_internal(&self, rule: &Rule, context: &RuleContext) -> Result<Value> {
        match &rule.rule_type {
            RuleType::Regex { pattern, flags } => {
                self.execute_regex_rule(pattern, flags.as_deref(), context)
            }
            RuleType::Range { min, max } => {
                self.execute_range_rule(min, max, context)
            }
            RuleType::Enum { values } => {
                self.execute_enum_rule(values, context)
            }
            RuleType::Length { min, max } => {
                self.execute_length_rule(*min, *max, context)
            }
            RuleType::Format { format } => {
                self.execute_format_rule(format, context)
            }
            RuleType::Custom { name, params } => {
                self.execute_custom_rule(name, params, rule, context)
            }
            RuleType::Composite { operator, rules } => {
                self.execute_composite_rule(operator, rules, context)
            }
        }
    }

    /// 执行正则表达式规则
    fn execute_regex_rule(&self, pattern: &str, _flags: Option<&str>, _context: &RuleContext) -> Result<Value> {
        let _regex = self.get_or_compile_regex(pattern)?;
        
        // 使用rand_regex生成匹配的字符串
        use rand_regex::Regex as RandRegex;
        let rand_regex = RandRegex::compile(pattern, 100)
            .map_err(|e| DataForgeError::generator(&format!("Failed to compile regex for generation: {}", e)))?;
        
        let mut rng = rand::thread_rng();
        let generated = rand_regex.sample(&mut rng);
        
        Ok(Value::String(generated))
    }

    /// 执行范围规则
    fn execute_range_rule(&self, min: &Value, max: &Value, _context: &RuleContext) -> Result<Value> {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        
        match (min, max) {
            (Value::Number(min_num), Value::Number(max_num)) => {
                if let (Some(min_f), Some(max_f)) = (min_num.as_f64(), max_num.as_f64()) {
                    let value = rng.gen_range(min_f..=max_f);
                    Ok(Value::Number(serde_json::Number::from_f64(value).unwrap()))
                } else {
                    Err(DataForgeError::validation("Invalid number range"))
                }
            }
            _ => Err(DataForgeError::validation("Range rule requires numeric min and max values")),
        }
    }

    /// 执行枚举规则
    fn execute_enum_rule(&self, values: &[Value], _context: &RuleContext) -> Result<Value> {
        use rand::seq::SliceRandom;
        let mut rng = rand::thread_rng();
        
        values.choose(&mut rng)
            .cloned()
            .ok_or_else(|| DataForgeError::validation("Empty enum values"))
    }

    /// 执行长度规则
    fn execute_length_rule(&self, min: Option<usize>, max: Option<usize>, _context: &RuleContext) -> Result<Value> {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        
        let min_len = min.unwrap_or(1);
        let max_len = max.unwrap_or(20);
        let length = rng.gen_range(min_len..=max_len);
        
        let chars: String = (0..length)
            .map(|_| rng.gen_range(b'a'..=b'z') as char)
            .collect();
        
        Ok(Value::String(chars))
    }

    /// 执行格式规则
    fn execute_format_rule(&self, format: &str, context: &RuleContext) -> Result<Value> {
        // 简单的格式替换实现
        let mut result = format.to_string();
        
        // 替换常见的占位符
        result = result.replace("{field_name}", &context.field_name);
        result = result.replace("{random_number}", &rand::random::<u32>().to_string());
        result = result.replace("{timestamp}", &chrono::Utc::now().timestamp().to_string());
        
        Ok(Value::String(result))
    }

    /// 执行自定义规则
    fn execute_custom_rule(&self, name: &str, _params: &HashMap<String, Value>, rule: &Rule, context: &RuleContext) -> Result<Value> {
        let handlers = self.custom_handlers.read().unwrap();
        
        if let Some(handler) = handlers.get(name) {
            let result = handler.handle(rule, context)?;
            result.value.ok_or_else(|| DataForgeError::generator("Custom rule handler returned no value"))
        } else {
            Err(DataForgeError::validation(&format!("Custom rule handler not found: {}", name)))
        }
    }

    /// 执行组合规则
    fn execute_composite_rule(&self, operator: &LogicalOperator, rules: &[Rule], context: &RuleContext) -> Result<Value> {
        match operator {
            LogicalOperator::And => {
                // 所有规则都必须成功，返回最后一个规则的结果
                let mut last_value = Value::Null;
                for rule in rules {
                    last_value = self.execute_rule_internal(rule, context)?;
                }
                Ok(last_value)
            }
            LogicalOperator::Or => {
                // 任意一个规则成功即可
                for rule in rules {
                    if let Ok(value) = self.execute_rule_internal(rule, context) {
                        return Ok(value);
                    }
                }
                Err(DataForgeError::generator("No rule in OR composite succeeded"))
            }
            LogicalOperator::Not => {
                // 规则不应该匹配，这里简单返回null
                Ok(Value::Null)
            }
        }
    }

    /// 获取或编译正则表达式
    fn get_or_compile_regex(&self, pattern: &str) -> Result<Regex> {
        // 首先尝试从缓存获取
        {
            let cache = self.regex_cache.read().unwrap();
            if let Some(regex) = cache.get(pattern) {
                return Ok(regex.clone());
            }
        }

        // 编译新的正则表达式
        let regex = Regex::new(pattern)
            .map_err(|e| DataForgeError::validation(&format!("Invalid regex pattern: {}", e)))?;

        // 存入缓存
        {
            let mut cache = self.regex_cache.write().unwrap();
            cache.insert(pattern.to_string(), regex.clone());
        }

        Ok(regex)
    }

    /// 验证规则
    fn validate_rule(&self, rule: &Rule) -> Result<()> {
        // 检查规则ID是否已存在
        {
            let rules = self.rules.read().unwrap();
            if rules.contains_key(&rule.id) {
                return Err(DataForgeError::validation(&format!("Rule ID already exists: {}", rule.id)));
            }
        }

        // 验证父规则是否存在
        if let Some(parent_id) = &rule.parent_id {
            let rules = self.rules.read().unwrap();
            if !rules.contains_key(parent_id) {
                return Err(DataForgeError::validation(&format!("Parent rule not found: {}", parent_id)));
            }
        }

        // 验证规则类型特定的内容
        match &rule.rule_type {
            RuleType::Regex { pattern, .. } => {
                Regex::new(pattern)
                    .map_err(|e| DataForgeError::validation(&format!("Invalid regex pattern: {}", e)))?;
            }
            RuleType::Range { min, max } => {
                if !min.is_number() || !max.is_number() {
                    return Err(DataForgeError::validation("Range rule requires numeric min and max values"));
                }
            }
            RuleType::Enum { values } => {
                if values.is_empty() {
                    return Err(DataForgeError::validation("Enum rule requires at least one value"));
                }
            }
            _ => {} // 其他类型暂不验证
        }

        Ok(())
    }

    /// 注册自定义规则处理器
    pub fn register_custom_handler(&self, handler: Arc<dyn CustomRuleHandler>) {
        let mut handlers = self.custom_handlers.write().unwrap();
        handlers.insert(handler.name().to_string(), handler);
    }

    /// 获取所有规则
    pub fn get_all_rules(&self) -> Vec<Rule> {
        let rules = self.rules.read().unwrap();
        rules.values().cloned().collect()
    }

    /// 根据标签查找规则
    pub fn find_rules_by_tag(&self, tag: &str) -> Vec<Rule> {
        let rules = self.rules.read().unwrap();
        rules.values()
            .filter(|rule| rule.tags.contains(&tag.to_string()))
            .cloned()
            .collect()
    }

    /// 获取规则继承链
    pub fn get_inheritance_chain(&self, rule_id: &str) -> Vec<String> {
        let mut chain = Vec::new();
        let mut current_id = rule_id.to_string();
        
        let rules = self.rules.read().unwrap();
        
        while let Some(rule) = rules.get(&current_id) {
            chain.push(current_id.clone());
            if let Some(parent_id) = &rule.parent_id {
                current_id = parent_id.clone();
            } else {
                break;
            }
        }
        
        chain.reverse();
        chain
    }

    /// 清理缓存
    pub fn clear_cache(&self) {
        let mut cache = self.regex_cache.write().unwrap();
        cache.clear();
    }
}

impl Default for RuleEngine {
    fn default() -> Self {
        Self::new(Arc::new(StringPool::default()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rule_engine_creation() {
        let string_pool = Arc::new(StringPool::default());
        let engine = RuleEngine::new(string_pool);
        
        assert_eq!(engine.get_all_rules().len(), 0);
    }

    #[test]
    fn test_add_rule() {
        let engine = RuleEngine::default();
        
        let rule = Rule {
            id: "test_rule".to_string(),
            name: "Test Rule".to_string(),
            rule_type: RuleType::Regex {
                pattern: r"\d{3}-\d{3}-\d{4}".to_string(),
                flags: None,
            },
            priority: 100,
            enabled: true,
            description: Some("Test phone number rule".to_string()),
            tags: vec!["phone".to_string()],
            parent_id: None,
        };

        assert!(engine.add_rule(rule).is_ok());
        assert_eq!(engine.get_all_rules().len(), 1);
    }

    #[test]
    fn test_execute_enum_rule() {
        let engine = RuleEngine::default();
        
        let rule = Rule {
            id: "enum_rule".to_string(),
            name: "Enum Rule".to_string(),
            rule_type: RuleType::Enum {
                values: vec![
                    Value::String("A".to_string()),
                    Value::String("B".to_string()),
                    Value::String("C".to_string()),
                ],
            },
            priority: 100,
            enabled: true,
            description: None,
            tags: vec![],
            parent_id: None,
        };

        engine.add_rule(rule).unwrap();

        let context = RuleContext {
            field_name: "test_field".to_string(),
            current_value: None,
            params: HashMap::new(),
            generation_history: Vec::new(),
        };

        let result = engine.execute_rule("enum_rule", &context).unwrap();
        assert!(result.matched);
        assert!(result.value.is_some());
        
        if let Some(Value::String(s)) = result.value {
            assert!(["A", "B", "C"].contains(&s.as_str()));
        }
    }

    #[test]
    fn test_rule_inheritance() {
        let engine = RuleEngine::default();
        
        // 添加父规则
        let parent_rule = Rule {
            id: "parent_rule".to_string(),
            name: "Parent Rule".to_string(),
            rule_type: RuleType::Length { min: Some(5), max: Some(10) },
            priority: 50,
            enabled: true,
            description: None,
            tags: vec![],
            parent_id: None,
        };
        engine.add_rule(parent_rule).unwrap();

        // 添加子规则
        let child_rule = Rule {
            id: "child_rule".to_string(),
            name: "Child Rule".to_string(),
            rule_type: RuleType::Length { min: Some(3), max: Some(8) },
            priority: 100,
            enabled: true,
            description: None,
            tags: vec![],
            parent_id: Some("parent_rule".to_string()),
        };
        engine.add_rule(child_rule).unwrap();

        let chain = engine.get_inheritance_chain("child_rule");
        assert_eq!(chain, vec!["parent_rule", "child_rule"]);
    }

    #[test]
    fn test_find_rules_by_tag() {
        let engine = RuleEngine::default();
        
        let rule1 = Rule {
            id: "rule1".to_string(),
            name: "Rule 1".to_string(),
            rule_type: RuleType::Length { min: Some(1), max: Some(10) },
            priority: 100,
            enabled: true,
            description: None,
            tags: vec!["test".to_string(), "demo".to_string()],
            parent_id: None,
        };

        let rule2 = Rule {
            id: "rule2".to_string(),
            name: "Rule 2".to_string(),
            rule_type: RuleType::Length { min: Some(1), max: Some(5) },
            priority: 50,
            enabled: true,
            description: None,
            tags: vec!["test".to_string()],
            parent_id: None,
        };

        engine.add_rule(rule1).unwrap();
        engine.add_rule(rule2).unwrap();

        let test_rules = engine.find_rules_by_tag("test");
        assert_eq!(test_rules.len(), 2);

        let demo_rules = engine.find_rules_by_tag("demo");
        assert_eq!(demo_rules.len(), 1);
    }
}